#include "Ringqueue.hpp"
#include <time.h>
#include <string>


struct ThreadData
{
    Ringqueue<int>* _rq;
    std::string _threadname;    
};

void* Comsumer(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    Ringqueue<int>* rq = td->_rq;
    std::string _threadname = td->_threadname;
    while(true)
    {
        int out;
        rq->Pop(&out);
        std::cout << _threadname << " get a data : " << out << std::endl;
        sleep(1);
    }
    return nullptr;
}

void* Producer(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    Ringqueue<int>* rq = td->_rq;
    std::string _threadname = td->_threadname;
    while(true)
    {
        int num = rand()%10;
        rq->Push(num);
        std::cout << _threadname << " push a data : " << num << std::endl;
    }
    return nullptr;
}

int main()
{
    srand((unsigned int)time(nullptr));
    Ringqueue<int>* rq = new Ringqueue<int>();
    
    pthread_t c[5], p[3];
    for(int i = 0; i < 5; ++i)
    {
        ThreadData* td = new ThreadData();
        td->_rq = rq;
        td->_threadname = "Comsumer-" + std::to_string(i);
        pthread_create(&c[i], nullptr, Comsumer, td);
    }
    for(int i = 0; i < 3; ++i)
    {
        ThreadData* td = new ThreadData();
        td->_rq = rq;
        td->_threadname = "Producer-" + std::to_string(i);
        pthread_create(&c[i], nullptr, Producer, td);
    }

    for(int i = 0; i < 5; ++i)
    {
        pthread_join(c[i], nullptr);
    }
    for(int i = 0; i < 3; ++i)
    {
        pthread_join(p[i], nullptr);
    }

    return 0;
}